package com.ipt.frm.pw.ajax;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Linkedin
 */
public class Linkedin extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Linkedin() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// https://www.linkedin.com/pub/dir/?first=raul&last=navascues-vega&search=Buscar

		response.setContentType("text/html");
		response.setCharacterEncoding(StandardCharsets.UTF_8.toString());

		PrintWriter out = response.getWriter();

		URL aURL = null;
		// Parametros del AJAX
		String nombre = request.getParameter("nombre");
		String ape1 = request.getParameter("ape1");
		String ape2 = request.getParameter("ape2");
		// Componer la URL para llamar a Linkedin
		String url = "https://www.linkedin.com/pub/dir/?first=" + nombre
				+ "&last=" + ape1 + "-" + ape2 + "&search=Buscar";
		// System.out.println(url);

		// Iniciar el parseo de la URL
		aURL = new URL(url);

		BufferedReader bfEntrada = new BufferedReader(new InputStreamReader(
				aURL.openStream()));

		String fileName = "webs/linkedin.html";
		File file = new File(fileName);
		String inputLine;

		// use FileWriter to write file
		FileWriter fw = new FileWriter(file.getAbsoluteFile());
		BufferedWriter bw = new BufferedWriter(fw);

		while ((inputLine = bfEntrada.readLine()) != null) {
			bw.write(inputLine);
			// bw.flush();
		}
		bw.close();
		bfEntrada.close();

		String everything = "";
		StringBuilder sb = null;
		BufferedReader br = new BufferedReader(new FileReader(
				"webs/linkedin.html"));
		try {

			String line = "";// br.readLine();
			sb = new StringBuilder();
			// line = new StringBuffer();

			while (line != null) {
				sb.append(line);
				// sb.append(System.lineSeparator());
				// line.append(br.readLine());
			}
			everything = sb.toString();
		} finally {
			br.close();
		}

		System.out.println(everything);
		/*
		 * ArrayList<String> listaDatos = new ArrayList<String>();
		 * 
		 * while ((inputLine = bfEntrada.readLine()) != null) {
		 * listaDatos.add(inputLine);
		 * 
		 * } bfEntrada.close();
		 */

	}

}
